import { NextResponse } from 'next/server'
import { jwtVerify } from 'jose'
import type { NextRequest } from 'next/server'

// 不需要验证的路径
const publicPaths = ['/login', '/api/auth/login']

export async function middleware(request: NextRequest) {
  // 检查是否是公开路径
  const isPublicPath = publicPaths.some(path => request.nextUrl.pathname.includes(path))
  if (isPublicPath) {
    return NextResponse.next()
  }

  // 获取 token
  const token = request.cookies.get('token')?.value

  if (!token) {
    // API 请求返回 401
    if (request.nextUrl.pathname.startsWith('/api/')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }
    // 页面请求重定向到登录
    return NextResponse.redirect(new URL('/login', request.url))
  }

  try {
    // 验证 token
    const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'your-secret-key')
    await jwtVerify(token, JWT_SECRET)
    return NextResponse.next()
  } catch (error) {
    // token 无效
    if (request.nextUrl.pathname.startsWith('/api/')) {
      return NextResponse.json(
        { error: 'token无效' },
        { status: 401 }
      )
    }
    return NextResponse.redirect(new URL('/login', request.url))
  }
}

// 配置需要进行中间件处理的路径
export const config = {
  matcher: [
    '/users/:path*',
    '/api/users/:path*',
    '/api/auth/logout'
  ]
} 